package cn.xej.health.user.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.xej.health.common.constant.AuthConstant;
import cn.xej.health.common.domain.UserDto;
import cn.xej.health.common.exception.Asserts;
import cn.xej.health.common.utils.CommonResult;
import cn.xej.health.common.utils.PageUtils;
import cn.xej.health.common.utils.Query;
import cn.xej.health.common.utils.ResultCode;
import cn.xej.health.user.dao.MenuDao;
import cn.xej.health.user.dao.RoleDao;
import cn.xej.health.user.dao.UserDao;
import cn.xej.health.user.entity.Menu;
import cn.xej.health.user.entity.Role;
import cn.xej.health.user.entity.User;
import cn.xej.health.user.feign.AuthFeignService;
import cn.xej.health.user.feign.TeamFeignService;
import cn.xej.health.user.service.UserService;
import cn.xej.health.user.vo.VoMenu;
import cn.xej.health.user.vo.VoUser;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xej
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private MenuDao menuDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private AuthFeignService authFeignService;

    @Autowired
    private TeamFeignService teamFeignService;

    @Override
    public void insertUser(User user) {
        this.insertUser(user);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<User> page = this.page(new Query<User>().getPage(params), new QueryWrapper<User>().orderByAsc("uuid"));
        return new PageUtils(page);
    }

    /**
     * 根据用户名获取通用用户信息
     * @param username
     * @return
     */
    @Override
    public UserDto loadUserByUsername(String username) {
        User user = this.getOne(new QueryWrapper<User>().eq("username",username));
        if (user != null){
            Role role = roleDao.selectById(user.getRid());
            List<Role> roleList = new ArrayList<>();
            roleList.add(role);
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user,userDto);
            userDto.setUuid(user.getUuid());
            if (CollUtil.isNotEmpty(roleList)){
                List<String> roleStrList = roleList.stream().map(item ->
                    item.getRid() + "_" + item.getRname()
                ).collect(Collectors.toList());
                userDto.setRoles(roleStrList);
            }
            return userDto;
        }
        return null;
    }

    @Override
    public CommonResult login(String username,String password) {
        if(StrUtil.isEmpty(username)||StrUtil.isEmpty(password)){
            Asserts.fail("用户名或密码不能为空！");
        }
        Map<String, String> params = new HashMap<>();
        params.put("client_id", AuthConstant.ADMIN_CLIENT_ID);
        params.put("client_secret","123456");
        params.put("grant_type","password");
        params.put("username",username);
        params.put("password",password);
        CommonResult restResult = authFeignService.postAccessToken(params);
//        if(ResultCode.SUCCESS.getCode()==restResult.getCode()&&restResult.getData()!=null){
////            updateLoginTimeByUsername(username);
//            insertLoginLog(username);
//        }
        return restResult;
    }

    /**
     * 获取用户信息
     * 获取用户菜单
     * @param username
     * @return
     */
    @Override
    public CommonResult queryInfo(String username) {
        Map<String,Object> map = new HashMap<>();
        User user = this.getOne(new QueryWrapper<User>().eq("username",username));

        CommonResult result = teamFeignService.getTeamByUserId(user.getUuid());


        List<Integer> menuIdList = menuDao.queryMenuIdList(user.getRid());
        //用户菜单
        List<Menu> menuList = menuDao.selectList(new QueryWrapper<Menu>().in("MENUID",menuIdList));
        //用户一级菜单
        List<Menu> level1 = menuList.stream().filter((menu) -> {
            if (result.getData() == null){
                return menu.getPid() == 0 && menu.getMenuid() != 7;
            }else {
                return menu.getPid() == 0;
            }
        }).map((menu) -> {
            menu.setChildren(getMenuChildren(menu,menuList,result));
            return menu;
        }).collect(Collectors.toList());

        List<VoMenu> voMenuList = level1.stream().map((menu) -> {
            VoMenu voMenu = new VoMenu();
            BeanUtils.copyProperties(menu,voMenu);
            voMenu.setId(String.valueOf(menu.getMenuid()));
            voMenu.setChildren(getVoMenuChildren(menu.getChildren()));
            return voMenu;
        }).collect(Collectors.toList());

        map.put("user",user);
        map.put("menu",voMenuList);
        return CommonResult.success(map);
    }

    /**
     * 查询所有用户
     * @param pageIndex
     * @param pageSize
     * @param searchName
     * @return
     */
    @Override
    public CommonResult queryList(Integer pageIndex,Integer pageSize,String searchName) {
        Map<String,Object> map = new HashMap<>();
        int startNum = (pageIndex-1)*pageSize+1;
        int endNum = pageIndex*pageSize;
        List<User> userList = userDao.queryUserList(startNum,endNum,searchName);
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().eq("rid", 2);
        queryWrapper.and(wrapper -> {
           wrapper.like("username",searchName).or().like("nickname",searchName);
        });
        Integer count = userDao.selectCount(queryWrapper);

        map.put("data",userList);
        map.put("total",count);
        return CommonResult.success(map);
    }

    private List<VoMenu> getVoMenuChildren(List<Menu> menuList) {
        List<VoMenu> voMenuList = menuList.stream().map((menu) -> {
            VoMenu voMenu = new VoMenu();
            BeanUtils.copyProperties(menu,voMenu);
            voMenu.setId(String.valueOf(menu.getMenuid()));
            voMenu.setChildren(getVoMenuChildren(menu.getChildren()));
            return voMenu;
        }).collect(Collectors.toList());

        return voMenuList;
    }

    /**
     * 获取孩子菜单
     * @param root
     * @param menuList
     * @return
     */
    private List<Menu> getMenuChildren(Menu root,List<Menu> menuList,CommonResult result) {
        List<Menu> children = menuList.stream().filter((menu) -> {
            if (result.getData() == null){
                return root.getMenuid().equals(menu.getPid()) && menu.getMenuid() != 6;
            }else {
                return root.getMenuid().equals(menu.getPid());
            }
        }).map((menu) -> {
            menu.setChildren(getMenuChildren(menu,menuList,result));
            return menu;
        }).collect(Collectors.toList());
        return children;


    }

    /**
     * 获取剩余团队长
     * @return
     */
    @Override
    public CommonResult queryCaptainList() {
        List<User> userList = userDao.queryCaptainList(2,1);
        return CommonResult.success(userList);
    }

    /**
     * 获取该团队的医生
     * @param tid
     * @return
     */
    @Override
    public CommonResult initMemberList(Integer tid,Integer pageIndex,Integer pageSize,String searchName) {
        Map<String,Object> map = new HashMap<>();
        int startNum = (pageIndex-1)*pageSize+1;
        int endNum = pageIndex*pageSize;
        List<User> userList = userDao.queryMemberList(tid,startNum,endNum,searchName);
        Integer count = userDao.memberCount(tid,searchName);

        map.put("data",userList);
        map.put("total",count);
        return CommonResult.success(map);
    }

    /**
     * 获取剩余的医生
     * @return
     */
    @Override
    public CommonResult initRemainUserList() {
        List<User> userList = userDao.queryRemainUserList();
        return CommonResult.success(userList);
    }

    /**
     * 根据用户编号获取用户信息
     * @param uuidList
     * @return
     */
    @Override
    public CommonResult getTeamDockerList(String uuidList) {
        List<Integer> list = JSONObject.parseArray(uuidList, Integer.class);

        List<User> userList = new ArrayList<>();

        list.forEach((item)->{
            User user = userDao.selectById(item);
            if (user.getStatus() == 1) {
                userList.add(user);
            }
        });
        return CommonResult.success(userList);
    }
}
